﻿using FibMatrix.Task;
using UnityEngine;

namespace FibMatrix
{
    [FM_Mono.IgnoreGen]
    public class DefaultAsyncLoadAssetPipe : IResourceLoadPipe
    {
        public DefaultAsyncLoadAssetPipe()
        {
        }

        public FMTask Handle(IResourcePipelineContext context, out ResourceError error)
        {
            error = ResourceError.None;

            DefaultLoadItem mainHint = context.item as DefaultLoadItem;

            if (mainHint.assetHandle == null)
            {
                ++mainHint.objRefCount;
                mainHint.assetHandle = new DefaultUAssetLoadHandle(Resources.LoadAsync(mainHint.itemID));
            }

            FMTask task = null;
            if (!mainHint.assetHandle.isCompleted)
            {
                task = PooledAsyncFMTask.Allocate(mainHint, null, GenerateAssetAsyncWork, null, null);
            }
            else
            {
                task = PooledCallLaterFMTask.Allocate(1);
            }
            task.Begin();
            return task;
        }

        private static IAsyncBase GenerateAssetAsyncWork(PooledAsyncFMTask task)
        {
            DefaultLoadItem item = (task.context as DefaultLoadItem);
            return item.assetHandle;
        }
    }
}
